package com.example.cobodynamicproxydemo.config;

import com.example.cobodynamicproxydemo.interceptors.UserApiInterceptor;
import com.example.cobodynamicproxydemo.service.UserApiDemoClient;
import com.example.cobodynamicproxydemo.service.UserApiExecution;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

@Slf4j
@Configuration
public class ProxyConfiguration implements InvocationHandler {

    @Resource
    private UserApiDemoClient userApiDemoClient;

    @Resource
    private List<UserApiInterceptor> interceptors;

    /**
     * 代理执行方法
     *
     * @param proxy  代理执行对象
     * @param method 代理方法
     * @param args   代理参数
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) {
        return new UserApiExecution(userApiDemoClient, interceptors).execute(method, args);
    }

    /**
     * 向spring注入经过代理的用户api
     *
     * @return UserApiDemoClient
     */
    @Bean("userApiProxyClient")
    public UserApiDemoClient getProxy() {
        return (UserApiDemoClient) Proxy.newProxyInstance(UserApiDemoClient.class.getClassLoader(), new Class[]{UserApiDemoClient.class}, this);
    }

}
